import java.util.PriorityQueue;

abstract class MyTask implements Runnable {
    public abstract void run();
}

class MyTimerTask1 implements Comparable<MyTimerTask1>{
    private MyTask myTask;
    private long time;

    public MyTimerTask1(MyTask myTask, long time) {
        this.myTask = myTask;
        this.time = time;
    }

    public long getTime() {
        return this.time;
    }

    public void run() {
        myTask.run();
    }

    @Override
    public int compareTo(MyTimerTask1 myTimerTask1) {
        return (int)(this.time - myTimerTask1.time);
    }
}

class MyTimer1 {

    private PriorityQueue<MyTimerTask1> queue = new PriorityQueue<>();

    private Object locker = new Object();

    public void schedule(MyTask myTask, long time) {
        synchronized(locker) {
            MyTimerTask1 myTimerTask1 = new MyTimerTask1(myTask, System.currentTimeMillis() + time);
            queue.offer(myTimerTask1);
            locker.notify();
        }
    }

    public MyTimer1() {
        Thread thread = new Thread(() -> {
            synchronized(locker) {
                while (true) {
                    while (queue.isEmpty()) {
                        try {
                            locker.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    MyTimerTask1 myTimerTask1 = queue.peek();
                    if (System.currentTimeMillis() < myTimerTask1.getTime()) {
                        try {
                            locker.wait(myTimerTask1.getTime() - System.currentTimeMillis());
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    } else {
                        myTimerTask1.run();
                        queue.poll();
                    }
                }
            }
        });
        thread.start();
    }
}

public class Demo3 {
    public static void main(String[] args) {
        MyTimer1 myTimer1 = new MyTimer1();

        myTimer1.schedule(new MyTask() {
            @Override
            public void run() {
                System.out.println(3000);
            }
        }, 3000);

        myTimer1.schedule(new MyTask() {
            @Override
            public void run() {
                System.out.println(2000);
            }
        }, 2000);

        myTimer1.schedule(new MyTask() {
            @Override
            public void run() {
                System.out.println(1000);
            }
        }, 1000);
    }
}
